#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include <GL/glew.h>
#include <GLFW/glfw3.h>

typedef struct FcStr FcStr;

struct FcStr
{
    size_t len;
    size_t pos;
    char* data;
    bool (*append)(FcStr* fc_str, const char* str);
};

bool fc_str_append(FcStr* fc_str, const char* str)
{
    bool ret = true;
    size_t len = strlen(str);
    // if current buffer is enough
    if (fc_str->pos + len <= fc_str->len ) {
        strcpy(fc_str->data+fc_str->pos, str);
        fc_str->pos += len;
    }
    // else: the current buffer is not enough, re-allocate
    else
    {
        char* new_data = realloc(fc_str->data, fc_str->len*2);
        if (new_data==NULL) { // abnormal case
            ret = false;
        } else {
            fc_str->data = new_data;
            fc_str->len *= 2;
            strcpy(fc_str->data+fc_str->pos, str);
            fc_str->pos += len;
        }
    }
    return ret;
}

FcStr* make_fc_str()
{
    FcStr* fc_str = (FcStr*)malloc(sizeof(FcStr));
    memset(fc_str, 0, sizeof(FcStr));
    
    fc_str->len = 128;
    fc_str->data = (char*)malloc(sizeof(char) * fc_str->len);
    memset(fc_str, 0, fc_str->len);
    
    fc_str->pos = 0;
    fc_str->append = fc_str_append;
    
    return fc_str;
}


typedef struct Shader
{
    const char* vertex_path;
    const char* fragment_path;
    unsigned int ID;
} Shader;

void make_shader(Shader** _shader, const char* vertex_pth, const char* fragment_pth) {
    
    Shader* shader = (Shader*)malloc(sizeof(Shader));
    memset((void*)shader, 0, sizeof(shader));
    //strcpy(shader->vertex_path, vertex_pth);
    //strcpy(shader->fragmentp_path, fragment_pth);
    shader->vertex_path = vertex_pth;
    shader->fragment_path = fragment_pth;
    
    // 1. retrieve the vertex/fragment source code from filePath
    const char* vertex_code;
    FILE* fin_v_shader = fopen(vertex_pth, "w");
    
    fclose(fin_v_shader);
    
    
    // write back
    *_shader = shader;
}

void processInput(GLFWwindow* window);

const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"\{\n"
"   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";

const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
"   FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";

void my_load_shader(unsigned int* _shaderProgram);

void framebuffer_size_callback(GLFWwindow* window, int width, int height);

int main() {
    Shader* shader = NULL;
    make_shader(&shader, "3.3.shader.vs", "3.3.shader.fs");
    printf("hello\n");
    printf("shader->vertex_path: %s\n", shader->vertex_path);
    printf("shader->fragment_path: %s\n", shader->fragment_path);
    
    FcStr* v_shader_pth = make_fc_str();
    v_shader_pth->append(v_shader_pth, shader->vertex_path);
    printf("--- v_shader_pth is: %s\n", v_shader_pth->data);
    
    
    printf("bye\n");
    
    return 0;
}

int main_old()
{
    printf("hello\n");
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    
    // Opgn GLFW Window
    GLFWwindow* window = glfwCreateWindow(800, 600, "My OpenGL Window", NULL, NULL);
    if (window==NULL) {
        printf("Open window failed\n");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    
    
    // Init GLEW
    glewExperimental = true;
    if (glewInit() != GLEW_OK) {
        printf("Init GLEW  failed.\n");
        glfwTerminate();
        return -1;
    }
    // the viewport seem useless: if I don't set, or set a smaller window, run same.
    //glViewport(0, 0, 800, 600);
    //glViewport(30, 30, 600, 500);
    
    float vertices[] = {
        -0.5f, -0.5f, 0.0f,
         0.5f, -0.5f, 0.0f,
         0.0f,  0.5f, 0.0f
    };

    //VAO
    unsigned int VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    
    //VBO
    unsigned int VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    
    // 4. 设定顶点属性指针
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    
    unsigned int shaderProgram;
    my_load_shader(&shaderProgram);
    glUseProgram(shaderProgram);
    
    // render loop
    while(!glfwWindowShouldClose(window)) {
        processInput(window);
        
        // clean screen and draw with blackboard color
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        //glUseProgram(shaderProgram);
        //glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    
    // de-allocate resources
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    
    glfwTerminate();
    return 0;
}

void processInput(GLFWwindow* window)
{
    // close window when `ESC` key pressed
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    {
        glfwSetWindowShouldClose(window, true);
    }
}

void my_load_shader(unsigned int* _shaderProgram)
{
    // vertex shader
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    
    // check for shader compile error
    int success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if(!success) {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog);
    }
    
    // fragment shader
    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    // check for shader compile errors
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if(!success) {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog);
    }
    
    // link shaders
    unsigned int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    
    // check for link errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
    }
    
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    
    // write back
    *_shaderProgram = shaderProgram;
}


// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}
